package com.strong.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

import java.io.File;
import java.net.URL;
import java.util.List;

@Configuration
public class MessageSourceConfig {

    /**
     * spring默认的国际化资源目录
     */
    @Value("${spring.messages.basename}")
    private String strMessageBasename;

    /**
     * spring默认的国际化资源编码
     */
    @Value("${spring.messages.encoding}")
    private String strMessageEncoding;

    @Bean(name = "messageSource")
    public ResourceBundleMessageSource getMessageSource() {
        ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
        resourceBundleMessageSource.setDefaultEncoding(strMessageEncoding);
        resourceBundleMessageSource.setBasenames(getMessageFiles(strMessageBasename));
        return resourceBundleMessageSource;
    }

    /**
     * 根据Resource名获取其中的资源文件数组
     *
     * @param strDirectory str目录
     * @return {@link String[] }
     */
    public static String[] getMessageFiles(String strDirectory) {
        URL url = ResourceUtil.getResource(strDirectory);

        Assert.isTrue(ObjUtil.isNotNull(url) && FileUtil.exist(url.getFile()), "未找到【{}】的国际化资源", strDirectory);
        List<File> files = FileUtil.loopFiles(url.getFile());

        Assert.notEmpty(files, "【{}】内的国际化资源为空", strDirectory);
        return files.stream().map(file -> strDirectory + "/" + FileNameUtil.getPrefix(file.getName())).toArray(String[]::new);
    }

}